<?php

namespace App\Services\PayPlus;

use App\Exception\MessageException;
use App\Model\ConfigPayPlatformParam;
use App\Utils\LoggerUtil;

class IndoPlusPayment
{

    private $merAccount;    // 商户号
    private $key;

    private $payUrl = "http://api.letspayfast.com/apipay";

    private $returnUrl = HOST . "/app/v1/pay/payPlus/syn_callback.php"; // 同步通知
    private $notifyUrl = HOST . "/app/v1/pay/payPlus/unsyn_callback.php";// 异步通知


    public function __construct($payPlatformID)
    {
        //获取支付通道参数
        $payPlatFormParams = ConfigPayPlatformParam::getPlatformParam($payPlatformID);
        $this->merAccount = $payPlatFormParams['mchId'] ?? '';
        $this->key = $payPlatFormParams['key'] ?? '';
    }


    public function createPayOrder($order)
    {
        $data = array(
            'amount' => $order['price'],//交易金额(元)
            'bankcode' => $order['productType'],
            'goods' => 'email:' . $order['email'] . '/name:' . $order['name'] . '/phone:' . $order['phone'],
            'mchId' => $this->merAccount,//商户标识
            'notifyUrl' => $this->notifyUrl,    //后台回调地址
            'orderNo' => $order['order_id'],//订单号
            'returnUrl' => $this->returnUrl,
            'product' => $order['productId'],//商品
        );
        $data['sign'] = $this->getSign($data);
        LoggerUtil::write('payPlus', $data);

        $ret = $this->curlPost($this->payUrl, $data);
        $retjson = json_decode($ret, true);
        LoggerUtil::write('payPlus', $ret);
        if ($retjson['retCode'] == 'SUCCESS') {
            return $retjson;
        } else {
            // \Tool::JSON(\CodeData::NEED_TIPS, '',$retjson['retMsg']);
            throw new MessageException($retjson['retMsg']);
        }
    }

    /**
     * 加签
     * @param $params
     * @return string
     */
    public function getSign($params)
    {
        $signKey = $this->key;
        ksort($params);
        $params = array_filter($params, function ($value) {
            return !empty($value);
        });
        $params['key'] = $signKey;
        $data = http_build_query($params);
        $data = urldecode($data);
        return strtoupper(md5($data));
    }


    public function curlPost($url, $post_data)
    {
        $ch = curl_init($url);
        $timeout = 6000;
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_FRESH_CONNECT, 1);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_FORBID_REUSE, 1);
        curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post_data));
        curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/x-www-form-urlencoded']);
        $ret = curl_exec($ch);
        curl_close($ch);

        return $ret;
    }
}